package com.msb.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.net.URI;


public class TestHdfs {

    public Configuration conf = null;
    public FileSystem fs = null;

    @Before
    public void conn() throws IOException, InterruptedException {

        conf = new Configuration(true);//new 对象
        //取环境变量，创建链接
        //fs = FileSystem.get(conf);
        //直接连接集群
        fs = FileSystem.get(URI.create("hdfs://node01:9000/"), conf, "root");

    }

    //创建，删除，查询
    @Test
    public void mkdir() throws IOException {
        Path dir = new Path("/laobi");
        if (fs.exists(dir)) {
            fs.delete(dir, true);
        }
        //创建目录
        fs.mkdirs(dir);

    }

    //删除文件
    @Test
    public  void delete() throws IOException {
        Path dir = new Path("/laobi");
        fs.delete(dir);
    }

    //上传文件
    @Test
    public void upload() throws Exception {
        //创建输入
        BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File("./data/hello.txt")));
        //创建输出
        Path outfile = new Path("/Test/out.txt");
        FSDataOutputStream output = fs.create(outfile);//创建了一个水管的输出位置
        IOUtils.copyBytes(input,output,conf,true);//java方法
    }

    //下载文件
    @Test
    public void getFileHdfs() throws IOException {
        //定义文件Hdfs下载的路径
        Path output = new Path("/Test/out.txt");

        //定义下载到win中文件路径
        Path input = new Path("D:/student.txt");

        //下载
        fs.copyToLocalFile(false, output, input, true);

        //关闭
        fs.close();

        System.out.println("plus下载成功");
    }


    @Test
    public void blocks() throws Exception {
        Path path = new Path("/Test/out.txt");
        FileStatus status = fs.getFileStatus(path);
        BlockLocation[] blks = fs.getFileBlockLocations(status, 0, status.getLen());
        for (BlockLocation blk:blks) {
            System.out.println(blk);
        }


    }

    @After
    public void close() throws IOException {
        fs.close();
    }
}
